"""
UI测试程序 - 最简版本
用于测试PyQt5基础功能
"""

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,
                             QWidget, QPushButton, QLabel, QTextEdit, QComboBox,
                             QSpinBox, QTableWidget, QTableWidgetItem, QTabWidget,
                             QGroupBox, QMessageBox)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont


class TestMainWindow(QMainWindow):
    """测试主窗口"""

    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.setWindowTitle("汽车数据系统 - UI测试版")
        self.setGeometry(100, 100, 1000, 700)

    def setup_ui(self):
        """设置界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QVBoxLayout(central_widget)

        # 标题
        title_label = QLabel("汽车之家数据爬取与展示系统")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setFont(QFont("Microsoft YaHei", 16, QFont.Bold))
        title_label.setStyleSheet("color: #2c3e50; padding: 10px;")
        main_layout.addWidget(title_label)

        # 控制区域
        control_group = QGroupBox("控制面板")
        control_layout = QHBoxLayout(control_group)

        # 汽车类型
        control_layout.addWidget(QLabel("汽车类型:"))
        self.car_type_combo = QComboBox()
        self.car_type_combo.addItems(["小轿车", "SUV", "MPV"])
        control_layout.addWidget(self.car_type_combo)

        # 数据量
        control_layout.addWidget(QLabel("数据量:"))
        self.page_size_spin = QSpinBox()
        self.page_size_spin.setRange(5, 50)
        self.page_size_spin.setValue(10)
        self.page_size_spin.setSuffix(" 条")
        control_layout.addWidget(self.page_size_spin)

        # 按钮
        self.test_btn = QPushButton("测试获取数据")
        self.test_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        self.test_btn.clicked.connect(self.test_data_fetch)
        control_layout.addWidget(self.test_btn)

        self.clear_btn = QPushButton("清空数据")
        self.clear_btn.setStyleSheet("""
            QPushButton {
                background-color: #e74c3c;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
        """)
        self.clear_btn.clicked.connect(self.clear_data)
        control_layout.addWidget(self.clear_btn)

        control_layout.addStretch()
        main_layout.addWidget(control_group)

        # 数据展示区域
        self.tab_widget = QTabWidget()

        # 表格视图
        self.table_widget = QTableWidget()
        columns = ["排名", "车名", "评分", "价格", "销量"]
        self.table_widget.setColumnCount(len(columns))
        self.table_widget.setHorizontalHeaderLabels(columns)
        self.table_widget.setAlternatingRowColors(True)
        self.tab_widget.addTab(self.table_widget, "表格视图")

        # 文本视图
        self.text_widget = QTextEdit()
        self.text_widget.setPlainText("欢迎使用汽车数据系统！\n\n点击'测试获取数据'按钮开始测试。")
        self.tab_widget.addTab(self.text_widget, "详细信息")

        main_layout.addWidget(self.tab_widget)

        # 状态信息
        self.status_label = QLabel("状态: 就绪")
        self.status_label.setStyleSheet("padding: 5px; background-color: #ecf0f1; border-radius: 3px;")
        main_layout.addWidget(self.status_label)

    def test_data_fetch(self):
        """测试数据获取"""
        car_type = self.car_type_combo.currentText()
        page_size = self.page_size_spin.value()

        self.status_label.setText(f"状态: 正在获取{car_type}数据...")
        QApplication.processEvents()

        try:
            # 尝试导入爬虫模块
            from crawler.car_crawler import CarCrawler

            crawler = CarCrawler()

            if car_type == "小轿车":
                cars = crawler.get_sedan_ranking(page_size)
            elif car_type == "SUV":
                cars = crawler.get_suv_ranking(page_size)
            else:
                # 创建模拟数据
                cars = self.create_mock_data(page_size)

            self.display_data(cars)
            self.status_label.setText(f"状态: 成功获取 {len(cars)} 条数据")

        except ImportError:
            # 如果爬虫模块不可用，使用模拟数据
            cars = self.create_mock_data(page_size)
            self.display_data(cars)
            self.status_label.setText(f"状态: 使用模拟数据 ({len(cars)} 条)")

        except Exception as e:
            QMessageBox.warning(self, "错误", f"数据获取失败:\n{str(e)}")
            self.status_label.setText("状态: 数据获取失败")

    def create_mock_data(self, count):
        """创建模拟数据"""
        mock_cars = []
        car_names = ["比亚迪秦PLUS", "大众朗逸", "丰田卡罗拉", "本田雅阁", "奔驰C级",
                     "宝马3系", "奥迪A4L", "特斯拉Model 3", "小鹏P7", "蔚来ET5"]

        for i in range(min(count, len(car_names))):
            car_data = {
                'rank': i + 1,
                'name': car_names[i],
                'score': 4.8 - i * 0.1,
                'price': f"{10 + i * 3}-{20 + i * 5}万",
                'sales': 25000 - i * 1500,
                'detail_url': f'https://www.autohome.com.cn/{1000 + i}'
            }
            mock_cars.append(car_data)

        return mock_cars

    def display_data(self, cars):
        """显示数据"""
        # 更新表格
        self.table_widget.setRowCount(len(cars))

        for row, car in enumerate(cars):
            # 处理不同数据格式
            if hasattr(car, 'rank'):  # CarInfo对象
                rank, name, score, price, sales = car.rank, car.name, car.score, car.price, car.sales
            else:  # 字典
                rank = car.get('rank', 0)
                name = car.get('name', '未知')
                score = car.get('score', 0.0)
                price = car.get('price', '暂无')
                sales = car.get('sales', 0)

            self.table_widget.setItem(row, 0, QTableWidgetItem(str(rank)))
            self.table_widget.setItem(row, 1, QTableWidgetItem(name))
            self.table_widget.setItem(row, 2, QTableWidgetItem(f"{score:.1f}"))
            self.table_widget.setItem(row, 3, QTableWidgetItem(str(price)))
            self.table_widget.setItem(row, 4, QTableWidgetItem(f"{sales:,}"))

        self.table_widget.resizeColumnsToContents()

        # 更新文本视图
        text_info = f"汽车数据详情 ({len(cars)} 条记录)\n"
        text_info += "=" * 40 + "\n\n"

        for i, car in enumerate(cars, 1):
            if hasattr(car, 'rank'):
                text_info += f"{i}. {car.name} (排名: {car.rank})\n"
                text_info += f"   评分: {car.score:.1f} | 价格: {car.price} | 销量: {car.sales:,}\n\n"
            else:
                text_info += f"{i}. {car.get('name', '未知')} (排名: {car.get('rank', 0)})\n"
                text_info += f"   评分: {car.get('score', 0.0):.1f} | 价格: {car.get('price', '暂无')} | 销量: {car.get('sales', 0):,}\n\n"

        self.text_widget.setPlainText(text_info)

    def clear_data(self):
        """清空数据"""
        self.table_widget.setRowCount(0)
        self.text_widget.setPlainText("数据已清空。\n\n点击'测试获取数据'按钮重新获取数据。")
        self.status_label.setText("状态: 数据已清空")


def main():
    """主函数"""
    app = QApplication(sys.argv)
    app.setFont(QFont("Microsoft YaHei", 9))

    # 设置样式
    app.setStyleSheet("""
        QGroupBox {
            font-weight: bold;
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            margin-top: 10px;
            padding-top: 10px;
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
            color: #2c3e50;
        }
    """)

    window = TestMainWindow()
    window.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()